package com.hut.oa.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.mail.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hut.oa.model.bean.AddressBook;
import com.hut.oa.model.bean.AddressDir;
import com.hut.oa.model.bean.Attachment;
import com.hut.oa.model.bean.EmailManage;
import com.hut.oa.model.bean.Status;
import com.hut.oa.model.bean.TaskFeedback;
import com.hut.oa.model.bean.TaskManage;
import com.hut.oa.model.bean.TaskUser;
import com.hut.oa.model.bean.User;
import com.hut.oa.model.bean.WorkAttend;
import com.hut.oa.model.dao.AttachmentDao;
import com.hut.oa.model.dao.address.AddressDao;
import com.hut.oa.model.dao.address.AddressDirDao;
import com.hut.oa.model.dao.mail.MailDao;
import com.hut.oa.model.dao.system.StatusDao;
import com.hut.oa.model.dao.task.TaskDao;
import com.hut.oa.model.dao.task.TaskfeedbackDao;
import com.hut.oa.model.dao.task.TaskuserDao;
import com.hut.oa.model.dao.user.DeptDao;
import com.hut.oa.model.dao.user.UserDao;
import com.hut.oa.model.mapper.AddressBookMapper;
import com.hut.oa.service.AddressService;
import com.hut.oa.service.AttachmentService;
import com.hut.oa.service.EmailService;
import com.hut.oa.service.FileService;
import com.hut.oa.service.SystemService;
import com.hut.oa.service.TaskService;

@Controller
@RequestMapping("/task")
public class TaskController {

	@Autowired
	private TaskDao tdao;
	
	@Autowired
	DeptDao dd;
	
	@Autowired
	private UserDao udao;

	@Autowired
	private AttachmentDao ad;

	@Autowired
	private AttachmentDao acdao;

	@Autowired
	private FileService fileser;

	@Autowired
	private AttachmentService attser;

	@Autowired
	private TaskuserDao tudao;

	@Autowired
	private TaskfeedbackDao tfdao;

	@Autowired
	private AttachmentService as;
	
	@Autowired
	private TaskService taskser;
	
	
	@RequestMapping(value = "/taskmanage")
	public String taskmanage(HttpSession session, Model model,
			@PageableDefault(value = 10, sort = { "tmId" }) Pageable pageable,@RequestParam(value="value",required=false)String value) {
		User u = (User) session.getAttribute("userinfo");
		if(null!=value){
			model.addAttribute("tasklist", tdao.findbytittle(pageable,value, u));
		}else{
			List<TaskManage> outtimelist=tdao.findbytime(new Date(),u);
			for (TaskManage taskManage : outtimelist) {
				taskManage.setTmStatus(5l);
				List<TaskUser> tulist=taskManage.getTaskuser();
				for (TaskUser taskUser : tulist) {
					taskUser.setTmStatus(5l);
				}
				tdao.save(taskManage);
			}
			model.addAttribute("tasklist", tdao.findByUser(pageable, u));
		}
		model.addAttribute("statu", 0);
		return "task/task";
	}
	//选择不同类型
	@RequestMapping(value = "/statustype")
	public String taskmanage(HttpSession session, Model model,
			@PageableDefault(value = 10, sort = { "tmId" }) Pageable pageable,
			@RequestParam(value="status",required=false)Long status) {
		User u = (User) session.getAttribute("userinfo");
		if(status==0){
			model.addAttribute("tasklist", tdao.findByUser(pageable, u));
			model.addAttribute("statu", 0);
		}else{
			model.addAttribute("tasklist", tdao.findByTmStatusAndUser(pageable,status,u));
			model.addAttribute("statu", status);	
		}
			return "task/task";
	}
	// 添加任务页面
	@RequestMapping(value = "/addtask")
	public String addtask(HttpSession session, Model model,
			@PageableDefault(value = 6, sort = { "tmId" }) Pageable pageable) {
		User u = (User) session.getAttribute("userinfo");
		model.addAttribute("userlist", udao.findByIdNot(u.getId()));
		return "task/addtask";
	}

	// 我的任务
	@RequestMapping(value = "/mytask")
	public String mytask(HttpSession session, Model model,
			@PageableDefault(value = 10, sort ="task.tmPushTime",direction=Direction.DESC) Pageable pageable,@RequestParam(value="value",required=false)String value) {
		User u = (User) session.getAttribute("userinfo");
		model.addAttribute("userlist", udao.findByIdNot(u.getId()));
		if(null!=value){
			model.addAttribute("tasklist", tudao.findbytittle(pageable, value, u));
		}else{
			model.addAttribute("tasklist", tudao.findByUser(pageable, u));
		}
		return "task/mytask";
	}

	// 查看界面
	@RequestMapping(value = "/showTask")
	public String showTask(HttpSession session, Model model, @RequestParam(value = "id", required = false) Long taskid,
			@PageableDefault(value = 6, sort = { "tmId" }) Pageable pageable) {
		User u = (User) session.getAttribute("userinfo");
		TaskManage task = tdao.findByUserAndTmId(u, taskid);
		model.addAttribute("task", task);
		StringBuffer username = new StringBuffer();
		List<TaskUser> tulist = tudao.findByTask(task);
		for (TaskUser taskUser : tulist) {
			username.append(taskUser.getUser().getRealName() + "、");
		}
		if (username.length() > 1) {
			model.addAttribute("username", username.substring(0, username.length() - 1).toString());
		} else {
			model.addAttribute("username", "");
		}
		return "task/showTask";
	}

	// 查看我的任务界面
	@RequestMapping(value = "/showmyTask")
	public String showmyTask(HttpSession session, Model model, @RequestParam(value = "id", required = false) Long tuid,
			@PageableDefault(value = 6, sort = { "tmId" }) Pageable pageable) {
		User u = (User) session.getAttribute("userinfo");
		TaskUser tu = tudao.findByUserAndTuid(u, tuid);

		TaskManage task = tdao.findOne(tu.getTask().getTmId());
		List<TaskUser> tulist = tudao.findByTask(task);

		model.addAttribute("tu", tu);
		StringBuffer username = new StringBuffer();
		for (TaskUser taskUser : tulist) {
			username.append(taskUser.getUser().getRealName() + "、");
		}
		if (username.length() > 1) {
			model.addAttribute("username", username.substring(0, username.length() - 1).toString());
		} else {
			model.addAttribute("username", "");
		}
		return "task/showTask";
	}

	// 新增任务
	@RequestMapping(value = "/savetask", method = RequestMethod.POST)
	public void savetask(HttpSession session, HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file,
			@PageableDefault(value = 6, sort = { "id" }) Pageable pageable, TaskManage task)
			throws IllegalStateException, IOException {
		User u = (User) session.getAttribute("userinfo");
		if (file.getSize() > 0) {
			if (task.getTmId() != null && task.getAttid() != null) {
				Attachment att = ad.findOne(task.getAttid());
				fileser.deletefolder(attser.getFilePath(att));
				ad.delete(task.getAttid());
			}
			Attachment att = attser.saveAttachment(file, u.getId(), "task");
			ad.save(att);
			task.setAttid(att.getId());
		}
		String shareuser = request.getParameter("shareuser").trim();
		List<TaskUser> list = new ArrayList<>();
		if (null != shareuser && !shareuser.equals("")) {
			String user[] = shareuser.split("、");
			if (user.length > 0) {
				for (String uid : user) {
					TaskUser tu = new TaskUser();
					User use = udao.findById(Long.parseLong(uid));
					tu.setUser(use);
					tu.setTask(task);
					list.add(tu);
				}
			}
			task.setTaskuser(list);
		}
		task.setUser(u);
		task.setTmPushTime(new Date());
		tdao.save(task);
	}
	// 编辑任务
	@RequestMapping(value = "/editTask")
	public String editTask(HttpSession session, Model model,
			@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam("id") Long taskid)
			throws IllegalStateException, IOException {
		User u = (User) session.getAttribute("userinfo");
		TaskManage task = tdao.findByUserAndTmId(u, taskid);
		model.addAttribute("task", task);

		StringBuffer username = new StringBuffer();
		StringBuffer userid = new StringBuffer();
		List<TaskUser> tulist = tudao.findByTask(task);
		for (TaskUser taskUser : tulist) {
			userid.append(taskUser.getUser().getId() + "、");
			username.append(taskUser.getUser().getRealName() + "、");
		}
		if(username.length()>1){
			model.addAttribute("username", username.substring(0, username.length() - 1).toString());
			model.addAttribute("userid", userid.substring(0, userid.length() - 1).toString());
		}else{
			model.addAttribute("username", "");
			model.addAttribute("userid","");
		}
		
		return "forward:/task/addtask";
	}
	//添加批注
	@RequestMapping(value = "/savepizhu")
	@ResponseBody
	public void savepizhu(HttpSession session, @RequestParam(value = "file", required = false) MultipartFile file,
			@RequestParam(value ="taskid", required = false) Long taskid,
			@RequestParam(value ="tfContent", required = false) String tfContent)
			throws IllegalStateException, IOException {
			User u = (User) session.getAttribute("userinfo");
			TaskFeedback tf=new TaskFeedback();
			tf.setTfContent(tfContent);
			tf.setTfTime(new Date());
			tf.setTask(tdao.findOne(taskid));
			tf.setUser(u);
			if(null!=file&&file.getContentType()!=""){
				Attachment att=as.saveAttachment(file, u.getId(), "task");
				att.setBusinessId(u.getId());
				att=ad.save(att);
				tf.setAttid(att.getId());
			}
			tfdao.save(tf);
	}
		
	// 修改任务进度
	@RequestMapping(value = "/statusupdate")
	@ResponseBody
	public void statusupdate(HttpSession session, @RequestParam(value = "file", required = false) MultipartFile file,
			@RequestParam(value ="taskid", required = false) Long taskid,
			@RequestParam(value ="tfContent", required = false) String tfContent,
			@RequestParam(value ="status", required = false) Long status,
			@RequestParam(value ="type", required = false) String type)
			throws IllegalStateException, IOException {
		User u = (User) session.getAttribute("userinfo");
		TaskFeedback tf=new TaskFeedback();
			tf.setStatus(status);
			tf.setTfContent(tfContent);
			tf.setTfTime(new Date());
			tf.setTask(tdao.findOne(taskid));
			tf.setUser(u);
			if(null!=file&&file.getContentType()!=""){
				Attachment att=as.saveAttachment(file, u.getId(), "task");
				att.setBusinessId(u.getId());
				att=ad.save(att);
				tf.setAttid(att.getId());
			}
			tfdao.save(tf);
	
			if(!type.equals("undefined")&&null!=type&&type!=""){
				TaskManage taskmanage=tdao.findOne(taskid);
				TaskUser tuser=tudao.findByUserAndTask(u, taskmanage);
				tuser.setTmStatus(status);
				tudao.save(tuser);
			}else{
				if(status==4){
					TaskManage taskmanage=tdao.findOne(taskid);
					List<TaskUser> tuserlist=taskmanage.getTaskuser();
					for (TaskUser taskUser : tuserlist) {
						taskUser.setTmStatus(4l);
					}
					taskmanage.setTaskuser(tuserlist);
					taskmanage.setTmStatus(4l);
					tdao.save(taskmanage);
				}else{
					taskser.updatestatus(status, taskid);
				}
			}
	}
	
	/**
	 * 任务报表
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping("/check")
	public String check(HttpSession session,String key,Long did,Model model, @PageableDefault(value = 8, sort = { "id" }) Pageable pageable){
		//User uswe=(User)session.getAttribute("userinfo");
		Page<User> users = udao.findAll(pageable);
		if (key!=null) {
			if (did!=null) {
				users = udao.findByRealNameAndDept(key, dd.findOne(did), pageable);
			}else{
				users = udao.findByRealNameLikeLike(key, pageable);
			}
		}
		List<User> us = users.getContent();
		List<Map<String, Object>> check = new ArrayList<>();
		Iterable<TaskUser> wa = tudao.findAll();
		for (User user : us) {
			Map<String, Object> s = new HashMap<>();
			s.put("name", user.getRealName());
			//任务总数
			int zon=0;
			for (TaskUser taskUser : wa) {
				if (taskUser.getUser().getId()==user.getId()) {
					zon+=1;
				}
			}
			s.put("zon", zon);
			//未处理
			int wei=0;
			for (TaskUser taskUser : wa) {
				if (taskUser.getUser().getId()==user.getId()&&taskUser.getTmStatus()==1l) {
					wei+=1;
				}
			}
			s.put("wei", wei);
			//已接收
			int receive=0;
			for (TaskUser taskUser : wa) {
				if (taskUser.getUser().getId()==user.getId()&&taskUser.getTmStatus()==2l) {
					receive+=1;
				}
			}
			s.put("receive", receive);
			//进行中 
			int conduct=0;
			for (TaskUser taskUser : wa) {
				if (taskUser.getUser().getId()==user.getId()&&taskUser.getTmStatus()==3l) {
					conduct+=1;
				}
			}
			s.put("conduct", conduct);
			//已完成
			int complete=0;
			for (TaskUser taskUser : wa) {
				if (taskUser.getUser().getId()==user.getId()&&taskUser.getTmStatus()==4l) {
					complete+=1;
				}
			}
			s.put("complete", complete);
			//未完成
			int nocomplete=0;
			for (TaskUser taskUser : wa) {
				if (taskUser.getUser().getId()==user.getId()&&taskUser.getTmStatus()==5l) {
					nocomplete+=1;
				}
			}
			s.put("nocomplete", nocomplete);
			check.add(s);
		}
		
		model.addAttribute("check", check);
		model.addAttribute("users", users);
		model.addAttribute("depts", dd.findAllByOrderByGrade());
		return "task/check";
	}
	
	// 删除任务
	@RequestMapping(value = "/taskdelete")
	public String taskdelete(HttpSession session, Model model, @RequestParam("id") String taskid){
		tdao.delete(Long.parseLong(taskid));
		return "forward:/task/taskmanage";
	}
	
	//主界面统计数据
	@ResponseBody
	@RequestMapping("/main")
	public int[] main(HttpSession session){
		User user = (User)session.getAttribute("userinfo");
		List<TaskUser>  tm=tudao.findByUser(user);
		System.out.println(tm);
		int[] ss=new int[5];
		int wei=0;
		int receive=0;
		int conduct=0;
		int complete=0;
		int nocomplete=0;
		for (TaskUser taskUser : tm) {
			//未处理
			if (taskUser.getTmStatus().equals(1l)) {
				wei+=1;
			}
			ss[0]=wei;
			//已接收
			if (taskUser.getTmStatus().equals(2l)) {
				receive+=1;
			}
			ss[1]=receive;
			//进行中 
			
			if (taskUser.getTmStatus().equals(3l)) {
				conduct+=1;
			}
			ss[2]=conduct;
			//已完成
			if (taskUser.getTmStatus().equals(4l)) {
				complete+=1;
			}
			ss[3]=complete;
			//未完成
			if (taskUser.getTmStatus().equals(5l)) {
				nocomplete+=1;
			}
			ss[4]=nocomplete;
		}
		return ss;
	}
}
